`
https://leetcode.cn/problems/merge-k-sorted-lists/
`

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
var mergeKLists = function (lists) {
  if (lists.length === 0) return null
  const dummy = {
    next: null
  }
  let p = dummy

  const getMinIndex = () => {
    let index = -1
    let minVal = Infinity
    for (let i = 0; i < lists.length; i++) {
      const l = lists[i]
      if (!l) continue
      if (l.val < minVal) {
        minVal = l.val
        index = i
      }
    }
    return index
  }

  while (true) {
    const index = getMinIndex()
    if (index !== -1) {
      p.next = new ListNode(lists[index].val)
      lists[index] = lists[index].next
      p = p.next
    } else {
      break
    }
  }

  return dummy.next
};